package com.czy.utilslib.view.viewPager;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewbinding.ViewBinding;
import androidx.viewpager2.widget.ViewPager2;

import com.czy.utilslib.debug.DebugUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;


/**
 * 用于展示ViewPager的Fragment
 * @param <SingleVB>        单个展示Fragment的ViewBinding
 * @param <F>               单个展示Fragment
 * @param <PA>              ViewPager2适配器
 * @param <PagersVB>        用于展示的PagersFragment的ViewBinding
 */
public abstract class PagersFragment
        <SingleVB extends ViewBinding, F extends SinglePagerFragment<SingleVB>, PA extends GenericPagerAdapter<F>, PagersVB extends ViewBinding>
        extends Fragment
        implements OnFragmentBarItemClickCallback {

    private static final String TAG = PagersFragment.class.getSimpleName();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        initViewBinding(inflater, container);

        init();

        setListener();

        return binding.getRoot();
    }

    //-------------------------------viewBinding-------------------------------

    protected PagersVB binding;
    // viewBinding反射
    private void initViewBinding(LayoutInflater inflater, ViewGroup container) {
        // 获取泛型的父类型
        Type superclass = getClass().getGenericSuperclass();
        // 获取参数类型
        assert superclass != null;
        Class<?> aClass = (Class<?>) ((ParameterizedType) superclass).getActualTypeArguments()[3];

        try {
            // 反射获取 inflate 方法
            Method method = aClass.getDeclaredMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
            // 填充Binding
            binding = (PagersVB) method.invoke(null, inflater, container, false);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    //-------------------------------init-------------------------------

    protected PA pagerAdapter;

    protected void init() {
        initView();
    }

    private void initView(){
        // 获取适配器的类
        Type superclass = getClass().getGenericSuperclass();
        assert superclass != null;
        Class<PA> adapterClass = (Class<PA>) ((ParameterizedType) superclass).getActualTypeArguments()[2];

        int fragmentCount = getFragmentCount(); // 你需要实现这个方法

        try {
            // 创建适配器实例
            pagerAdapter = adapterClass.getDeclaredConstructor(FragmentManager.class, Lifecycle.class, int.class)
                    .newInstance(getChildFragmentManager(), getLifecycle(), fragmentCount);

            // 设置适配器
            setViewPagerAdapter(pagerAdapter);

        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException("Failed to create adapter", e);
        } catch (java.lang.InstantiationException e) {
            throw new IllegalArgumentException("Adapter class must extend GenericPagerAdapter");
        }
    }

    // 抽象方法：获取ViewPager
    protected abstract ViewPager2 getViewPager();
    protected abstract int getFragmentCount();

    // 设置适配器
    private void setViewPagerAdapter(PA adapter){
        if(adapter == null){
            DebugUtil.logE(TAG,"adapter是空，返回");
            return;
        }

        // 设置适配器
        getViewPager().setAdapter(adapter);

        // 注册适配器
        getViewPager().registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                // 点击Bar之后调用切换
                onBarPageSelected(position);
                if(adapter.fragmentList.get(position) != null){
                    adapter.fragmentList.get(position).changeToDo(position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }
        });
    }

    // 在切换的时候调用
     protected abstract void onBarPageSelected(int position);

    //-------------------------------setListener-------------------------------

    protected void setListener() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    //-------------------------------callback-------------------------------

    @Override
    public void onFragmentBarItemClick(int selectedItem) {
        getViewPager().setCurrentItem(selectedItem, true);
    }
}
